import { defineStore } from 'pinia'
import { configStore } from './config'
import pinia from './index'
import router from '@/router'
import { storageRead, storageSet } from '@/utils/storage'
import { dynamicProcessRO } from '@/router/utils'

type CacheInfoInter = {
  path: string
  name: any
  meta?: {
    title?: string
    keepAlive?: boolean
    icon?: string
  }
}

const useLabComCache = defineStore('labComCache', () => {
  const cacheData: Ref<CacheInfoInter[]> = ref(storageRead('tag') || [])
  const keepAliveInclude: Ref<CacheInfoInter[]> = ref([])

  const setCacheData = ({ path: copyPath, name, meta }: CacheInfoInter) => {
    const path = copyPath.replaceAll(/\/?:.*/g, '')
    const isFlag = cacheData.value.some(c => c.name === name)
    !isFlag && cacheData.value.push({ path, name, meta })
    meta?.keepAlive && setKeepAlive({ path, name, meta })
    configStore.config.isCache && storageSet('tag', cacheData.value)
  }

  const setKeepAlive = (cacheInfo: CacheInfoInter) => keepAliveInclude.value.push(cacheInfo)

  const closeCLRCacheData = (path: string, startTag: string) => {
    const index = cacheData.value.findIndex(c => c.path === path)
    const currentPath = dynamicProcessRO(router.currentRoute.value.path)
    const currentIndex = cacheData.value.findIndex(c => c.path === currentPath)
    switch (startTag) {
      case 'current':
        cacheData.value.splice(index, 1)
        currentPath === path
          ? cacheStorageOper(cacheData.value[index]?.path || cacheData.value[cacheData.value.length - 1]?.path)
          : cacheStorageOper()
        break
      case 'left':
        cacheData.value.splice(0, index)
        cacheStorageOper(index > currentIndex ? cacheData.value[0].path : '')
        break
      case 'right':
        cacheData.value.splice(index + 1, cacheData.value.length - index)
        cacheStorageOper(index < currentIndex ? cacheData.value[cacheData.value.length - 1].path : '')
        break
    }
  }

  const closeOtherCacheData = (path: string) => {
    cacheData.value = cacheData.value.filter(c => path === c.path)
    cacheStorageOper(path)
  }

  const closeAllCacheData = () => {
    cacheData.value = []
    cacheStorageOper()
    router.replace('/')
  }

  const cacheStorageOper = (path?: string) => {
    path && router.push(path)
    configStore.config.isCache && storageSet('tag', cacheData.value)
  }

  return {
    cacheData,
    keepAliveInclude,
    setCacheData,
    closeCLRCacheData,
    closeOtherCacheData,
    closeAllCacheData
  }
})

export const labComCacheStore = useLabComCache(pinia)
